﻿using System;
using CDOP.Model;
using CDOP.Utility;

namespace CDOP
{
    public partial class UserRegistration : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                if (Session["LoggedUser"] == null)
                    Response.Redirect("Login.aspx");
                else if (((UserDetails)Session["LoggedUser"]).UserType.Type.ToLower() != "admin")
                    Response.Redirect("SearchPatient.aspx");
        }

        protected void BtnSubmitClick(object sender, EventArgs e)
        {
            var authDb = new Authentication();
            var userDb = new UserDetails();
            var userType = ddUserType.SelectedItem.Text;
            var isUserNameDuplicated = authDb.IsUserNameExist(txtUserName.Text);
            if (isUserNameDuplicated)
            {
                lblStatus.Text = "A user already exists with the same name.<br/>Please Enter a different value for user name.";
            }
            else
            {
                var userToSave = new UserDetails
                                     {
                                         First_Name = txtFirstName.Text,
                                         Last_name = txtLastName.Text,
                                         Email = txtEmail.Text,
                                         Contact_Number = txtContactNumber.Text
                                     };
                var authenticationToSave = new Authentication
                                               {
                                                   User_Name = txtUserName.Text,
                                                   Password = Helper.Encrypt(txtPassword.Text)
                                               };
                userToSave.Authentication.Add(authenticationToSave);

                var userId = userDb.SaveUser(userToSave, userType);
                if (userToSave.id > 0)
                    lblStatus.Text = "User Saved Successfully";

            }
        }
    }
}